package com.senyint.sys.utils.json;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json处理及格式类
 * 
 * @author NaiFei Wang
 * @version 1.0
 */
public class JSONUtil {

	public static String jsonFromObject(Object object) throws JsonProcessingException {
		ObjectMapper om = new ObjectMapper();
		config(om);
		return om.writeValueAsString(object);
	}

	public static <T> T jsonToObject(String json, Class<T> c) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper om = new ObjectMapper();
		configReturnList(c, om);
		config(om);
		return om.readValue(json, c);
	}

	public static String jsonFromObjectWithDateFormat(Object object, String formatString) throws JsonProcessingException {
		ObjectMapper om = new ObjectMapper();
		om.setDateFormat(new SimpleDateFormat(formatString));
		config(om);
		return om.writeValueAsString(object);
	}

	public static <T> T jsonToObjectWithDateFormat(String json, Class<T> c, String formatString) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper om = new ObjectMapper();
		configReturnList(c, om);
		config(om);
		om.setDateFormat(new SimpleDateFormat(formatString));
		return om.readValue(json, c);
	}

	public static JsonNode jsonToNode(String json) throws JsonProcessingException, IOException {
		ObjectMapper om = new ObjectMapper();
		return om.readTree(json);
	}

	public static <T> T convert(Object fromValue, Class<T> toValueType) {
		ObjectMapper om = new ObjectMapper();
		return om.convertValue(fromValue, toValueType);
	}

	public static <T> T convert(Object fromValue, Class<T> toValueType, String formatString) {
		ObjectMapper om = new ObjectMapper();
		om.setDateFormat(new SimpleDateFormat(formatString));
		return om.convertValue(fromValue, toValueType);
	}

	private static void config(ObjectMapper om) {
		/*
		 * 忽略不存在的属性
		 */
		om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// om.configure(Feature.AUTO_DETECT_FIELDS, true);
		// om.setPropertyNamingStrategy(new PropertyNamingStrategyDefultCase());
	}

	private static <T> void configReturnList(Class<T> c, ObjectMapper om) {
		Class<?>[] interfaces = c.getInterfaces();
		boolean b = false;
		for (Class<?> cl : interfaces) {
			b = List.class.isAssignableFrom(cl);
			if (b) {
				break;
			}
		}
		if (b) {
			/*
			 * 允许对象强转list
			 */
			om.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
		}
	}
}